package _base0to1;

/**
 * 67. 二进制求和
 */
public class No67 {
    public String addBinary(String a, String b) {
        int n = a.length();
        int m = b.length();

        StringBuilder temp = new StringBuilder();
        temp.append("0".repeat(Math.abs(n - m)));

        if (n < m) a = temp.append(a).toString();
        else b = temp.append(b).toString();

        temp = new StringBuilder("0");
        for (int i = 0; i < Math.max(n, m); i++) {
            temp.append(a.charAt(i) - '0' + b.charAt(i) - '0');
        }

        char[] charArray = temp.toString().toCharArray();
        for (int i = charArray.length - 1; i >= 0; i--) {
            if (charArray[i] == '2') {
                charArray[i] = '0';
                charArray[i - 1]++;
            } else if (charArray[i] == '3') {
                charArray[i] = '1';
                charArray[i - 1]++;
            }
        }
        return charArray[0] == '0' ? new String(charArray, 1, charArray.length - 1) : new String(charArray);
    }
}
